package com.cjd.common.utils

import android.content.Context
import android.text.TextUtils
import com.cjd.common.okhttp3.FileConverterFacory
import com.cjd.common.okhttp3.GsonConverterFactory
import okhttp3.MediaType
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/9/24
 * description
 */
object RetrofitUtils {

    private var retrofit: Retrofit? = null
    private var BASE_URL: String? = null

    fun getBaseUrl(): String? {
        return BASE_URL
    }

    fun init(
        context: Context,
        baseUrl: String,
        encryptType: String? = null,
        encryptKey: String? = null
    ) {
        if (TextUtils.isEmpty(baseUrl)) {
            throw RuntimeException("baseUrl not null")
        }
        if (retrofit == null) {
            BASE_URL = baseUrl
            OkHttpUtils.init(context, encryptType, encryptKey)

            retrofit = Retrofit.Builder().client(OkHttpUtils.getClient()!!)
                .addConverterFactory(FileConverterFacory.create())
                .addConverterFactory(retrofit2.converter.gson.GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(BASE_URL!!).build()

        }
    }


    private fun getRetrofit(): Retrofit {
        if (retrofit == null)
            throw RuntimeException("please on application init!")
        return retrofit as Retrofit
    }

    fun <T> create(clazz: Class<T>): T {
        return getRetrofit().create(clazz)
    }

    fun convertParams(
        params: Map<String, Any?>,
        contentType: MediaType? = MediaType.parse("application/json;charset=utf-8")
    ): RequestBody {
        return RequestBody.create(
            contentType,
            GsonUtils.instance().toJson(params)
        )
    }
}